package api

import (
	"net/http"

	"xlib/log"

	D "TCP/define"

	"github.com/gin-gonic/gin"
)

func loggerDebug() gin.HandlerFunc {
	return func(c *gin.Context) {
		if c.Request.Method == http.MethodOptions {
			c.Header("Access-Control-Allow-Origin", "*")
			c.Header("Access-Control-Allow-Headers", "Accept, Content-Type, Origin, X-Requested-With")
			c.Header("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, PATCH, DELETE")

			c.Set("Content-Type", "application/json")
			c.AbortWithStatus(http.StatusNoContent)
			return
		}

		c.Header("Access-Control-Allow-Origin", "*")
		c.Header("Access-Control-Allow-Headers", "Authorization, Content-Type, Cookie")
		c.Header("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, PATCH, DELETE")

		log.Debugf("Client IP: %s, Method: [%s], URL: %s", c.ClientIP(), c.Request.Method, c.Request.URL.RequestURI())
		c.Next()
	}
}

func authentication() gin.HandlerFunc {
	return func(c *gin.Context) {
		apiKey := c.Query(apiKey)
		if apiKey == "" {
			log.Error("'apikey' is nil")
			c.Abort()
			D.ErrorCodeWithExtraInfo(c, http.StatusOK, D.EcParamMissing, D.EmParamMissing, "'apikey' is nil")
			return
		}

		if apiKey != auth {
			log.Error(apiKey)

			c.Abort()
			D.ErrorCodeWithMsg(c, http.StatusOK, D.EcAuthentication, D.EmAuthentication)
			return
		}

		c.Next()
	}
}
